package org.yinxue.swing.unit.util;

import org.yinxue.swing.core.util.StringUtil;
import org.yinxue.swing.unit.constant.UnitConstant;
import org.yinxue.swing.unit.model.ClassDesc;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zengjian
 * @create 2018-04-29 9:31
 * @since 1.0.0
 */
public class UnitUtil extends StringUtil implements UnitConstant {

    // pointSummaryAccountService.delete(pointSummaryAccountEntity.getCustNum(), null, pointSummaryAccountEntity.getPointType(),ss.get(123,321));
    // pointSummaryAccountService.delete(pointSummaryAccountEntity.getCustNum(), ss.get(ssf.get(1,2),321), null, pointSummaryAccountEntity.getPointType()),

    public static String[] extractEntryParam(String methodLine) {
        String subLine = methodLine.substring(methodLine.indexOf("(") + 1, methodLine.lastIndexOf(")"));
        // 采用 ","的方式来进行切分，判断一个","是否有效的条件为该","前是否第一个碰见的符号为( ,那说明是无效的",",继续查询
        List<String> list = new LinkedList<>();
        char[] cs = subLine.toCharArray();
        int cursor = 0;
        for (int i = 0; i < cs.length; i++) {
            int leftBracket = -1;
            int rightBracket = -1;
            if (cs[i] == ',') {
                // 往前寻找，计算( )的数量，如果( )的数量相等说明该,有效，如果不相等，说明为无效,，
                for (int j = i; j > 0; j--) {
                    if (cs[j] == '(') {
                        leftBracket++;
                    } else if (cs[j] == ')') {
                        rightBracket++;
                    }
                }
                if (leftBracket == rightBracket) {
                    list.add(new String(Arrays.copyOfRange(cs, cursor, i)).trim());
                    cursor = i + 1;
                }
            }
        }
        // 循环结束后 cusor已经到了最后的一个","上，那么就可以取得数组最后的部分
        list.add(new String(Arrays.copyOfRange(cs, cursor, cs.length)).trim());
        return list.toArray(new String[list.size()]);
    }


    /**
     * 根据获得的classLine，截取到className
     *
     * @param classLine
     * @return
     */
    public static String findClassName(String classLine) {
        return classLine.replaceAll(RETAIN_CLASS_NAME, " ").trim().split(" ")[0];
    }

    /**
     * 文本转换为实体类
     *
     * @param context
     * @return
     */
    public static String[] parseArray(String context) {
        return context.split("\n");
    }

    /**
     * 文本转换为实体类并且去除两侧的空格及注释类
     *
     * @param context
     * @return
     */
    public static String[] parseArrayAndTrim(String context) {
        String[] lines = parseArray(context);
        return trimSpaceAndNote(lines);
    }

    public static String parseContext(String[] lines) {
        StringBuilder builder = new StringBuilder(1024);
        for (int i = 0, length = lines.length; i < length; i++) {
            builder.append(lines[i] + "\n");
        }
        return builder.toString();
    }

    private static String[] trimSpaceAndNote(String[] lines) {
        // 删除所有行的前后空格，以及注释语句
        for (int i = 0; i < lines.length; i++) {
            // TODO 特例处理 ^\}
            lines[i] = lines[i].replaceAll("//[\\s\\S]*", "").trim().replaceAll("\n", "");
        }
        return lines;
    }

    /**
     * 以"{"标识符寻找其结束符 "}"下标 <br>
     *
     * @param start 开始坐标
     * @param lines 目标数组
     * @return 返回结束符坐标
     */
    public static int getEndLineIndex(int start, String[] lines) {
        int count = 0;
        int end = 0;
        // 利用{}来判断结束的地方
        for (int i = start; i < lines.length; i++) {

            // 说明是注释语句，跳过

            // 特殊情况的处理
            //
            //       /*  if (EcoType.ECO_TYPE_LAOX.getInitParamValue().equals(ecoType)) {
            //         accountInfoBeanList.add(pointCoupon);
            //       return accountInfoBeanList;
            //        }*/

            if (lines[i].startsWith("//") || lines[i].startsWith("/*") || lines[i].endsWith("*/")) {
                continue;
            }

            if (lines[i].contains("}") && lines[i].contains("{")) {
                continue;
            }

            if (!(lines[i].contains("}") || lines[i].contains("{"))) {
                continue;
            }

            if (lines[i].contains("{")) {
                count++;
            }
            if (lines[i].contains("}")) {
                count--;
            }

            if (count == 0) {
                end = i;
                break;
            }
        }
        if (end == 0 /*|| end == lines.length-2*/) { // TODO 如果扫描到了结尾都没结束，说明该｝写在一行里了 构造器这种情况
            return start;
        }
        return end;
    }

    /**
     * 寻找数组中以什么标志开头，以何标志结束的短语文本 <br>
     *
     * @param index 数组开始下标，默认为0
     * @param header 起始行
     * @param endMark 起始行的结束标志
     * @param lines 文本数组
     * @return 返回完整method 或者class header文本
     */
    public static String findBlockByLine(int index, String header, String endMark, String[] lines) {
        // 如果像 接口类，接口方法没有 {,只有方法定义，直接返回
        if (!header.contains(endMark)) {
            return header;
        }

        int start = index;
        int end = index;
        int offset = index;
        while (true) {
            if (offset != 0 && lines[--offset].startsWith(header)) {
                start--;
            } else {
                offset = index;
                break;
            }
        }

        while (true) {
            if (lines[offset++].contains(endMark)) {
                break;
            } else {
                end++;
            }
        }
        String[] headerLines = Arrays.copyOfRange(lines, start, end + 1);
        return parseContext(headerLines);
    }


    /**
     * 根据所给的方法行，找到相应的方法名 <br>
     *
     * @param methodLine 方法行或者methodPharse 例如: public void setStatus(String status) {
     * @return 方法名
     */
    @Deprecated
    public static String getMethodName(String methodLine) {
        Pattern pattern = Pattern.compile("[ >]+([a-zA-Z_0-9]+)\\s*\\(");
        Matcher matcher = pattern.matcher(methodLine);
        String methodName = null;
        while (matcher.find()) {
            methodName = matcher.group(1)/*.replaceAll("\\(| +", "")*/;
        }
        return methodName;
    }

    // pointSummaryAccountService.delete(pointSummaryAccountEntity.getCustNum(), null, pointSummaryAccountEntity.getPointType(),ss.get(123,321));
    // pointSummaryAccountService.delete(pointSummaryAccountEntity.getCustNum(), ss.get(ssf.get(1,2),321), null, pointSummaryAccountEntity.getPointType()),

    public static String[] resolveEntryParamArray(String methodLine) {
        String subLine = extractBracketLineAndTrimN(methodLine);
        // 采用 ","的方式来进行切分，判断一个","是否有效的条件为该","前是否第一个碰见的符号为( ,那说明是无效的",",继续查询
        List<String> list = new LinkedList<>();
        char[] cs = subLine.toCharArray();
        int cursor = 0;
        for (int i = 0; i < cs.length; i++) {
            int leftBracket = -1;
            int rightBracket = -1;
            if (cs[i] == ',') {
                // 往前寻找，计算( )的数量，如果( )的数量相等说明该,有效，如果不相等，说明为无效,，
                for (int j = i; j > 0; j--) {
                    if (cs[j] == '(' || cs[j] == '<') {
                        leftBracket++;
                    } else if (cs[j] == ')' || cs[j] == '>') {
                        rightBracket++;
                    }
                }
                if (leftBracket == rightBracket) {
                    list.add(new String(Arrays.copyOfRange(cs, cursor, i)).trim());
                    cursor = i + 1;
                }
            }
        }
        // 循环结束后 cusor已经到了最后的一个","上，那么就可以取得数组最后的部分
        list.add(new String(Arrays.copyOfRange(cs, cursor, cs.length)).trim());
        // 剔除无参的情况，cusor为0的情况一是没有参数，二是一个参数
        if ("".equals(list.get(0))) {
            return new String[]{};
        }
        return list.toArray(new String[list.size()]);
    }

    /**
     * 去除多余的括号
     *
     * @return
     */
    public static String trimeUnneededBracket(String methodPharse) {
        String methodLine = methodPharse;
        char[] arr = methodLine.toCharArray();
        int left = 0;
        int right = 0;
        for (char c : arr) {
            if (c == '(') {
                left++;
            }
            if (c == ')') {
                right++;
            }
        }
        if (right > left) {
            // 收缩right-left次
            for (int i = 0; i < right - left; i++) {
                methodLine = methodLine.substring(0, methodPharse.lastIndexOf(")"));
            }
        }
        // 最后删除掉换行符,换行符可能是 会引用一个变量比如  Stirng\nstr 此处如果替换\n为空则可能识别不出该字
        return methodLine.replaceAll("\n", " ");
    }

    public static String extractBracketLineAndTrimN(String methodPharse) {
        String methodLine = trimeUnneededBracket(methodPharse);
        return methodLine.substring(methodPharse.indexOf("(") + 1, methodLine.lastIndexOf(")")).replaceAll("\n", " ");
    }

    /**
     * 取构造器方法入参 <br>
     * 取普通(含静态)方法入参 <br>
     *
     * @param regex
     * @param value
     * @return
     */
    public static Map<String, String> getMethodEntryParams(String methodPharse) {
        Pattern patternVar = null;
        if (!methodPharse.contains("{")) {
            patternVar = Pattern.compile(VARS_ABSTRACT_METHOD);
        } else {
            patternVar = Pattern.compile(VARS_METHOD);
        }
        Map<String, String> properties = new LinkedHashMap<>();
        Matcher matcher1 = patternVar.matcher(methodPharse);
        if (matcher1.find()) { //运行1次
            String subPharse = matcher1.group();
            String[] entryParams = resolveEntryParamArray(subPharse);
            for (String entryParam : entryParams) {
                String line = entryParam;
                if (line.startsWith("@")) {
                    line = line.replaceAll(VARS_ANNOTATION, "").trim();
                    // 如果注解没有()需要再替换一次
                    if (line.startsWith("@")) {
                        line = line.replaceAll(VARS_ANNATATION_NOPARAM, "").trim();
                    }
                }
                if (line.startsWith("final")) {
                    line = line.replaceAll("final", "").trim();
                }
                String var = "";
                String type = "";

                if (!line.contains("...")) {
                    if (!line.endsWith("[]")) {
                        int index = line.lastIndexOf(" ");
                        var = line.substring(index + 1).trim();
                        type = line.substring(0, index + 1).trim();
                    } else {
                        // 以[] 符号结尾的数组 e.g. Map<String, Object> arr[]
                        var = line.substring(line.lastIndexOf(" ") + 1, line.lastIndexOf("["));
                        type = line.substring(0, line.lastIndexOf(" ")).trim() + "[]";
                    }
                } else {
                    // 加入变长数组的判断 e.g. String ...fields
                    line = line.replaceAll(" *", "");
                    int index = line.lastIndexOf("...");
                    var = line.substring(index + 3).trim();
                    // 截取后转换为数组类型
                    type = line.substring(0, index) + "[]";
                }

                if (type.contains("<")) {
                    type = type.replaceAll("<[\\s\\S]*>", "").trim();
                }
                properties.put(var, type);
            }
        }
        return properties;
    }

    /**
     * 生成单元测试的静态方法
     *
     * @param context
     * @return
     */
    public static String getUnitContext(String context) {
        ClassDesc definition = new ClassDesc(context);
        // 未解析到 simplename 说明是空java文件
        if (definition.isEmptyObject()) {
            return "";
        }
        return definition.buildUnitTestContext();
    }

    public static ClassDesc convert2Definition(String context) {
        return new ClassDesc(context);
    }

    public static String getReturnType(String methodLine) {
        String line = "";
        if (methodLine.contains("public ")) {
            if (!methodLine.contains("static ")) {
                line = methodLine.replaceAll("public ", "").trim().split(" ")[0];
            } else {
                line = methodLine.replaceAll("(public |static )", "").trim().split(" ")[0];
            }
        } else {
            line = methodLine.split(" ")[0];
        }
        if (line.contains("<")) {
            return line.substring(0, line.indexOf("<"));
        }
        return line;
    }

    public static void getEnumFieldMap(String context) {
//        // 删除换行符
//        String context2 = context.replaceAll("\n", "");
//        // 删除注释内容
//        context2 = context2.replaceAll("\\\\*\\*[\\s\\S]*\\*/", "");
//        // 截取从{到;这段内容
//        context2 = context2.substring(context2.indexOf("{")+1, context2.indexOf(";"));
//        char[] arr = context2.toCharArray();
        Pattern pattern = Pattern.compile("[A-Z_]+\\([0-9, \"]*\\)");
        Matcher matcher = pattern.matcher(context);
        while (matcher.find()) {
            String text = matcher.group();
            System.out.println(text);
        }

    }

    public static void main(String[] args) {
        // getDatabaseName("jdbc:mysql://127.0.0.1:3306/family?useAffectedRows=true&useSSL=true");
        // extractEntryParam("pointSummaryAccountService.delete(pointSummaryAccountEntity.getCustNum(), null, pointSummaryAccountEntity.getPointType(),ss.get(123,321));");
        String s = "pointSummaryAccountService.delete(pointSummaryAccountEntity.getCustNum(), ss.get(ssf.get(1,2),321), null, pointSummaryAccountEntity.getPointType())";
        s = "pointSummaryAccountService.delete()";
        extractEntryParam(s);

        System.out.println("\n".equals(System.getProperty("line.separator")));
        System.out.println();
        /*String returnType = getReturnType("public int hello();");
        System.out.println(returnType);*/
        // 提取 enum field
//        getEnumFieldMap("package com.suning.camp.rsf.constants;\n" +
//                "\n" +
//                "public enum CampErrorCode {\n" +
//                "\n" +
//                "    /**\n" +
//                "     * 内部错误:{0}\n" +
//                "     */\n" +
//                "    CA000001(\"内部错误:{0}\"),\n" +
//                "    /**\n" +
//                "     * RSF接口调用异常:{0}\n" +
//                "     */\n" +
//                "    CA000002(\"RSF接口调用异常:{0}\"),\n" +
//                "    /**\n" +
//                "     * ESB接口调用异常:{0}\n" +
//                "     */\n" +
//                "    CA000003(\"ESB接口调用异常:{0}\"),\n" +
//                "    /**\n" +
//                "     * 校验错误：参数{0}不能为空\n" +
//                "     */\n" +
//                "    CA100001(\"参数{0}不能为空\"),\n" +
//                "    /**\n" +
//                "     * 校验错误：参数{0}格式不合法{1}\n" +
//                "     */\n" +
//                "    CA100002(\"参数{0}格式不合法{1}\"),\n" +
//                "    /**\n" +
//                "     * 校验错误：参数{0}不存在\n" +
//                "     */\n" +
//                "    CA100003(\"参数{0}不存在\"),\n" +
//                "    /**\n" +
//                "     * 校验错误：参数{0}长度不合法,应为{1}位\n" +
//                "     */\n" +
//                "    CA100004(\"参数{0}长度不合法,应为{1}位\"),\n" +
//                "\n" +
//                "    /**\n" +
//                "     * 商户会员不存在\n" +
//                "     */\n" +
//                "    CA200001(\"商户会员不存在\"),\n" +
//                "    /**\n" +
//                "     * 会员编号为非商户会员\n" +
//                "     */\n" +
//                "    CA200002(\"会员编号为非商户会员\"),\n" +
//                "    /**\n" +
//                "     * 商户账户已存在\n" +
//                "     */\n" +
//                "    CA200003(\"商户账户已存在\"),\n" +
//                "    /**\n" +
//                "     * 商户云钻账户创建失败\n" +
//                "     */\n" +
//                "    CA200004(\"商户云钻账户创建失败\"),\n" +
//                "    /**\n" +
//                "     * 商户云钻账户已冻结\n" +
//                "     */\n" +
//                "    CA200005(\"商户云钻账户已冻结\"),\n" +
//                "    /**\n" +
//                "     * 商户云钻账户未开通\n" +
//                "     */\n" +
//                "    CA200006(\"商户云钻账户未开通\"),\n" +
//                "    /**\n" +
//                "     * 商户账户余额不足\n" +
//                "     */\n" +
//                "    CA200007(\"商户账户余额不足\"),\n" +
//                "    /**\n" +
//                "     * 活动未创建 \n" +
//                "     */\n" +
//                "    CA200008(\"活动未创建\"),\n" +
//                "    /**\n" +
//                "     * 活动已撤消\n" +
//                "     */\n" +
//                "    CA200009(\"活动已撤消\"),\n" +
//                "    /**\n" +
//                "     * 活动已下架\n" +
//                "     */\n" +
//                "    CA200010(\"活动已下架\"),\n" +
//                "    /**\n" +
//                "     * 活动加回额大于其创建及追加累加额\n" +
//                "     */\n" +
//                "    CA200011(\"活动加回额大于其创建及追加累加额\"),\n" +
//                "    /**\n" +
//                "     * 未查询到记录\n" +
//                "     */\n" +
//                "    CA200012(\"未查询到记录\"),\n" +
//                "    /**\n" +
//                "     * 账户异常信息修改失败\n" +
//                "     */\n" +
//                "    CA200013(\"账户异常信息更新失败\"),\n" +
//                "    /**\n" +
//                "     * 商户云钻账户状态可用，不允许解冻操作\n" +
//                "     */\n" +
//                "    CA200014(\"商户云钻账户状态可用，不允许解冻操作\"),\n" +
//                "\n" +
//                "    /**\n" +
//                "     * 商户云钻账户状态更新失败\n" +
//                "     */\n" +
//                "    CA200015(\"商户云钻账户状态更新失败\"),\n" +
//                "\n" +
//                "    /**\n" +
//                "     * 商户账户解冻记录状态变更失败\n" +
//                "     */\n" +
//                "    CA200016(\"商户账户解冻记录状态变更失败\"),\n" +
//                "\n" +
//                "    /**\n" +
//                "     * 商户账户解冻记录后台操作日志失败\n" +
//                "     */\n" +
//                "    CA200017(\"商户账户冻结/解冻记录后台操作日志失败\"),\n" +
//                "\n" +
//                "    /**\n" +
//                "     * 商户云钻账户所处状态，不允许冻结操作\n" +
//                "     */\n" +
//                "    CA200018(\"商户云钻账户所处状态，不允许冻结操作\"),\n" +
//                "\n" +
//                "    /**\n" +
//                "     * 商户账户可用余额小于商户账户批次余额\n" +
//                "     */\n" +
//                "    CA200019(\"商户账户可用余额小于商户账户批次余额\"),\n" +
//                "    /**\n" +
//                "     * 活动已撤单下架或过期\n" +
//                "     */\n" +
//                "    CA200020(\"活动已撤单下架或过期\"),\n" +
//                "\n" +
//                "    /**\n" +
//                "     * 活动已撤单下架或过期\n" +
//                "     */\n" +
//                "    CA200021(\"批次过期，调用活动下架失败\"),\n" +
//                "\n" +
//                "    /**\n" +
//                "     * 账户不存在对应的过期批次记录\n" +
//                "     */\n" +
//                "    CA200022(\"账户不存在对应的过期批次记录\"),\n" +
//                "    /**\n" +
//                "     * 撤单加回额度大于原扣减额度\n" +
//                "     */\n" +
//                "    CA200023(\"撤单加回额度大于原扣减额度\"),\n" +
//                "    /** 重复处理 */\n" +
//                "    CA200024(\"重复处理\"),\n" +
//                "    /** 退货回滚额度不等于退货额度 */\n" +
//                "    CA200025(\"退货回滚额度不等于退货额度\"),\n" +
//                "    \n" +
//                "    /** 更新会员积分余额汇总信息失败 */\n" +
//                "    CA200026(\"更新会员积分余额汇总账户信息失败\"),\n" +
//                "    /** 更新会员积分余额账户信息失败 */\n" +
//                "    CA200027(\"更新会员积分余额账户信息失败\"),\n" +
//                "    /** 更新会员积分余额账户信息失败 */\n" +
//                "    CA200028(\"更新券账户信息失败\"),\n" +
//                "    \n" +
//                "    /** 更新账户类型失败 */\n" +
//                "    CA200029(\"更新账户类型失败\"),\n" +
//                "    \n" +
//                "    /** 更新账户类型对应业态失败*/\n" +
//                "    CA200030(\"更新账户类型对应业态失败\"),\n" +
//                "    \n" +
//                "    /**\n" +
//                "     * 货币类型错误码:新增货币类型信息失败\n" +
//                "     */\n" +
//                "    CA200031(\"新增货币类型信息失败\"),\n" +
//                "    /**\n" +
//                "     * 货币类型错误码:更新货币类型信息失败\n" +
//                "     */\n" +
//                "    CA200032(\"更新货币类型信息失败\"),\n" +
//                "    \n" +
//                "    /** 更新储值账户失败 */\n" +
//                "    CA200033(\"更新储值账户失败\"),\n" +
//                "    \n" +
//                "    /** 更新储值账户交易事件失败 */\n" +
//                "    CA200034(\"更新储值账户交易事件失败\"),\n" +
//                "    \n" +
//                "   \n" +
//                "    /** 未知的批次类型 */\n" +
//                "    CA200035(\"未知的批次类型\"),\n" +
//                "    \n" +
//                "    \n" +
//                "    /** 更新积分汇总表失败 */\n" +
//                "    CA200036(\"更新积分汇总表失败\"),\n" +
//                "    \n" +
//                "    /** 更新冻结积分批次表失败 */\n" +
//                "    CA200037(\"更新冻结积分批次表失败\"),\n" +
//                "    \n" +
//                "    /**\n" +
//                "     * 退货试算扣减失败\n" +
//                "     */\n" +
//                "    CA200038(\"退货试算扣减失败\"),\n" +
//                "    \n" +
//                "    /**\n" +
//                "     * 未知错误\n" +
//                "     */\n" +
//                "    CA999999(\"未知错误\");\n" +
//                "\n" +
//                "    private String desc;\n" +
//                "\n" +
//                "    public String getDesc() {\n" +
//                "        return this.desc;\n" +
//                "    }\n" +
//                "\n" +
//                "    CampErrorCode(String desc) {\n" +
//                "        this.desc = desc;\n" +
//                "    }\n" +
//                "}\n");

    }

    public static Map<String, ClassDesc> resolveSuperClass(String mainClassPharse, ClassDesc classDesc) {
        if (mainClassPharse.contains("\n")) {
            mainClassPharse = mainClassPharse.replaceAll("\n", " ");
        }

        Map<String, ClassDesc> map = new LinkedHashMap<>();
        // 先消除泛型内的 extends 干扰
        String mainClassHolder = mainClassPharse.replaceAll("<[^=]*>", "");
        if (!mainClassHolder.contains(" implements ") && !mainClassHolder.contains(" extends ")) {
            classDesc.genericType.put(classDesc.simpleName, getGenerics(mainClassPharse));
            return map;
        }

        if (mainClassPharse.contains(" extends ")) {
            String mainText = mainClassPharse.substring(0, mainClassPharse.indexOf(" extends ")).trim();
            // 添加子类自带的泛型
            classDesc.genericType.put(classDesc.simpleName, getGenerics(mainText));

            String text = mainClassPharse.substring(mainClassPharse.indexOf(" extends ")).replace(" extends ", "").trim();
            if (mainClassPharse.contains(" implements ")) {
                text = text.substring(0, text.lastIndexOf(" implements "));
            }
            // 开始探测类别
            char[] arr = text.toCharArray();
            int length = arr.length;
            int count = 0;
            int cursor = 0;
            for (int i = 0; i < length; i++) {
                if (arr[i] == '<') {
                    count++;
                    continue;
                }
                if (arr[i] == '>') {
                    count--;
                    continue;
                }
                if (count == 0 && (arr[i] == ',' || arr[i] == '{' || i == length - 1)) {
                    String superClass = new String(Arrays.copyOfRange(arr, cursor, i == length - 1 && arr[i] != '{' ? length : i)).trim();
                    if (superClass.contains("<")) {
                        // 取得这部分的泛型
                        List<String> list = getGenerics(superClass);
                        superClass = superClass.replaceAll("<[\\s\\S]*>", "");
                        // 存储类名及泛型
                        classDesc.genericType.put(superClass, list);
                    }
                    // TODO 补全全名称
                    superClass = fullClassName(superClass, classDesc);
                    map.put(superClass, null);
                    cursor = i + 1;
                }
            }
        }

        if (mainClassPharse.contains(" implements ") && !mainClassPharse.contains(" extends ")) {
            String mainText = mainClassPharse.substring(0, mainClassPharse.indexOf(" implements ")).trim();
            classDesc.genericType.put(classDesc.simpleName, getGenerics(mainText));
        }

        if (mainClassPharse.contains(" implements ")) {
            String text = mainClassPharse.substring(mainClassPharse.indexOf(" implements ")).replace(" implements ", "").trim();
            char[] arr = text.toCharArray();
            int length = arr.length;
            int count = 0;
            int cursor = 0;
            for (int i = 0; i < length; i++) {
                if (arr[i] == '<') {
                    count++;
                    continue;
                }
                if (arr[i] == '>') {
                    count--;
                    continue;
                }
                if (count == 0 && (arr[i] == ',' || arr[i] == '{')) {
                    String superClass = new String(Arrays.copyOfRange(arr, cursor, i)).trim();
                    if (superClass.contains("<")) {
                        List<String> list = getGenerics(superClass);
                        superClass = superClass.replaceAll("<[\\s\\S]*>", "");
                        classDesc.genericType.put(superClass, list);
                    }
                    superClass = fullClassName(superClass, classDesc);
                    map.put(superClass, null);
                    cursor = i + 1;
                }
            }
        }

        return map;
    }

    public static String fullClassName(String simpleName, ClassDesc classDesc) {
        // 从classDesc的导入包中去寻找
        String superClassImport = classDesc.sourceImportLines.get(simpleName);
        String fullClassName = findFullName(superClassImport);
        return fullClassName == null ? simpleName : fullClassName;
    }

    private static String findFullName(String importPath) {
        if (importPath == null || !importPath.startsWith("import")) {
            return null;
        }
        return importPath.substring(importPath.indexOf("import") + "import".length(), importPath.lastIndexOf(";")).trim();
    }

    /**
     * 获得该行中的泛型 <br>
     *
     * @param superClass
     * @return
     */
    private static List<String> getGenerics(String superClass) {
        Pattern pattern = Pattern.compile("<[^=]*>");
        Matcher matcher = pattern.matcher(superClass);
        List<String> list = new ArrayList<>();
        while (matcher.find()) {
            String matchText = matcher.group();
            matchText = matchText.substring(matchText.indexOf("<") + 1, matchText.indexOf(">"));
            if (matchText.contains(",")) {
                String[] strArray = matchText.split(",");
                for (int j = 0, size = strArray.length; j < size; j++) {
                    if (strArray[j].contains(" extends ")) {
                        strArray[j] = strArray[j].substring(0, strArray[j].indexOf(" extends ")).trim();
                    } else {
                        // no change
                    }
                }
                list = Arrays.asList(strArray);
            } else {
                if (matchText.contains(" extends ")) {
                    matchText = matchText.substring(0, matchText.indexOf(" extends ")).trim();
                }
                list.add(matchText);
            }
        }
        return list;
    }

    /**
     * 提取方法的抛出异常 <br>
     *
     * @param methodHeader
     * @return 有时返回list集合，无时返回空list
     */
    public static List<String> getMethodExceptions(String methodHeader) {
        List<String> results = new LinkedList<>();
        if (!methodHeader.contains("throws")) {
            return results;
        }
        // 此处替换为1个空格，否则无法判断  throws 前后
        // 考虑到接口方法中的抛异常是以;结尾，没有实现类，所以需要判断下
        // 如果还有别的未知的情况就返回空的结果集
        String text = methodHeader.replaceAll("\n", " ").trim();
        if (text.endsWith("{")) {
            text = text.substring(text.lastIndexOf("throws") + "throws".length(), text.lastIndexOf("{")).trim();
        } else if (text.endsWith(";")) {
            text = text.substring(text.lastIndexOf("throws") + "throws".length(), text.lastIndexOf(";")).trim();
        } else {
            return results;
        }
        if (text.contains(",")) {
            String[] strArray = text.split(",");
            for (int i = 0, length = strArray.length; i < length; i++) {
                strArray[i] = strArray[i].trim();
                results = Arrays.asList(strArray);
            }
        } else {
            results.add(text);
        }
        return results;
    }

    /**
     * 分析class语句块，得到相关类的泛型<br>
     * <pre>
     * 1.如果整个语句不包含 < 直接返回
     * 2.如果包含，就按类、继承类、接口类逐个处理
     * </pre>
     *
     * @param classHeader
     * @return
     */
//    public static Map<String,List<String>> getGeneric(String classHeader, ClassDesc classDesc) {
//        if (classHeader.contains("\n")) {
//            classHeader = classHeader.replaceAll("\n", " ");
//        }
//        if (classHeader.contains("<")){
//            return new LinkedHashMap<>();
//        }
//        if (classHeader.contains(" extends ")){
//
//        }
//
//
//
//
//
//    }
}

